package com.jia.interceptor;

import cn.hutool.core.util.StrUtil;
import com.alibaba.fastjson2.JSON;
import com.jia.vo.Result;
import com.jia.vo.ResultCodeEnum;
import jakarta.servlet.http.HttpServletRequest;
import jakarta.servlet.http.HttpServletResponse;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.RedisTemplate;
import org.springframework.stereotype.Component;
import org.springframework.web.servlet.HandlerInterceptor;
import org.springframework.web.servlet.ModelAndView;


/**
 * 业务
 * 1:拦截器实现
 * 2:aop的通知 前置 后置 环绕 异常 最终
 * 3：前端用户登录到前置进行拦截
 * 4：拦截之后判断是否登录，是存入threadlocal中，重新保存redis中，否则跳转到登录页面
 */
@Component
public class InterceptorHandler implements HandlerInterceptor {



    @Autowired
    private RedisTemplate<String,String> redisTemplate;

    @Override
    //前置
    public boolean preHandle(HttpServletRequest request, HttpServletResponse response, Object handler) throws Exception {
        //放过webful中的options
        if(StrUtil.equals(request.getMethod(),"OPTIONS")){
            return true;
        }
        //请求头token
        String token = request.getHeader("token");
        if(StrUtil.isBlank(token)){
            error(response);
            return false;
        }
        //从redis中取出
        String userJson = redisTemplate.opsForValue().get("admin:login:"+token);
        if(StrUtil.isBlank(userJson)){
            error(response);
            return false;
        }
        return true;
    }

    @Override
    //后置
    public void postHandle(HttpServletRequest request, HttpServletResponse response, Object handler, ModelAndView modelAndView) throws Exception {
        HandlerInterceptor.super.postHandle(request, response, handler, modelAndView);
    }

    @Override
    //最终
    public void afterCompletion(HttpServletRequest request, HttpServletResponse response, Object handler, Exception ex) throws Exception {

    }

    public void error(HttpServletResponse response){
        Result result=Result.build(null, ResultCodeEnum.LOGIN_AUTH);
        response.setCharacterEncoding("utf-8");
        response.setContentType("application/json");
        try {
            response.getWriter().write(JSON.toJSONString(result));
        } catch (Exception e) {
            e.printStackTrace();
        }
    }
}
